package com.moyuaninfo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.moyuaninfo.model.MessageModel;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 邱祥霸
 * @date 2020/4/8
 */
public class TxtUtils {
    /** 根目录*/
    private static final String DIR = "G:\\ymal\\";

    /**
     * 保存数据到txt 文本
     *
     * @param message 数据内容
     *
     * @author 邱祥霸
     * @date 2020/4/8
     */
    public static void write(String message){
        MessageModel messageModel = new MessageModel();
        messageModel.setMessage(message);
        messageModel.setCreateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss SSS"));

        String fileName = DIR + DateUtil.format(new Date(), "yyyy-MM-dd")  + ".txt";
        File file = new File(fileName);
        FileOutputStream fos = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file, true);
            FileChannel channel = fos.getChannel();
            ByteBuffer src = Charset.forName("utf8").encode(JSONUtil.toJsonStr(messageModel) + "\r\n");

            int length;
            while ((length = channel.write(src)) !=0 ) {
                System.out.println("写入长度:" + length);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取数据
     * @return java.util.List<java.lang.String>
     *
     * @author 邱祥霸
     * @date 2020/4/8
     */
    public static List<String> read() {
        String fileName = DIR + DateUtil.format(new Date(), "yyyy-MM-dd")  + ".txt";

        List<String> result= new ArrayList<>();
        try {
            List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
            for (String str : lines ) {
                if (StringUtils.isNotBlank(str)) {
                    MessageModel messageModel = JSONUtil.toBean(str, MessageModel.class);
                    result.add(messageModel.getMessage());
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i ++) {
            write("你好世界" + i);
        }

//        read();
    }
}
